package org.example.proxy;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import org.example.Model.RequestData;
import org.example.Model.ResponseData;
import org.example.Model.ServiceMetaInfo;
import org.example.RPCApplication;
import org.example.config.RPCConfig;
import org.example.constant.RpcConstant;
import org.example.registry.RegistryFactory;
import org.example.registry.IRegistry;
import org.example.serialize.Serializer;
import org.example.serialize.SerializerFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;

public class UserServiceDynamicProxy implements InvocationHandler {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 指定序列化器
//        Serializer serializer = new JdkSerializer();
        RPCConfig rpcConfig = RPCApplication.getConfig();
        final Serializer serializer = SerializerFactory.getInstance(rpcConfig.getSerializer());
        // 准备发送数据
        RequestData requestData = new RequestData().builder()
                .serviceName(method.getDeclaringClass().getName())
                .methodName(method.getName())
                .parameterTypes(method.getParameterTypes())
                .args(args)
                .build();
        // 序列化请求数据
        try {
            byte[] bytes = serializer.serialize(requestData);

            // 从注册中心获取服务提供者请求地址
            IRegistry registry = RegistryFactory.getInstance(rpcConfig.getRegistryConfig().getRegistry());
            ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
            serviceMetaInfo.setServiceName(requestData.getServiceName());
            serviceMetaInfo.setServiceVersion(RpcConstant.DEFAULT_SERVICE_VERSION);
            List<ServiceMetaInfo> services = registry.discovery(serviceMetaInfo.getServiceKey());
            if(CollUtil.isEmpty(services)) {
                throw new RuntimeException(serviceMetaInfo.getServiceName() + " 服务提供者不存在");
            }
            ServiceMetaInfo serviceMetaInfo1 = services.get(0);

            // 发送请求
/*            HttpResponse httpResponse = HttpRequest.post("http://localhost:8080")
                    .body(bytes)
                    .execute();*/
            HttpResponse httpResponse = HttpRequest.post(serviceMetaInfo1.getServiceAddress())
                    .body(bytes)
                    .execute();
            ResponseData responseData = serializer.deserialize(httpResponse.bodyBytes(), ResponseData.class);
            return responseData.getData();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
